package com.example.tencentTrain;

/**
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 *  如果不存在公共前缀，返回空字符串 ""。
 *
 *  示例 1：
 * 输入：strs = ["flower","flow","flight"]
 * 输出："fl"
 *
 *  示例 2：
 * 输入：strs = ["dog","racecar","car"]
 * 输出：""
 * 解释：输入不存在公共前缀。
 */
public class Leetcode14_LongestCommonPrefix {
    public static void main(String[] args) {
        String[] strs = {"flower", "flow", "flight"};
        strs = new String[] {"dog", "racecar", "car"};
        strs = new String[] {"ab", "a"};
        System.out.println(new Solution().longestCommonPrefix(strs));
    }

    static class Solution {
        /**
         * 纵向扫描法
         * @param strs
         * @return
         */
        public String longestCommonPrefix(String[] strs) {
            int res = 0;
            int minLen = Integer.MAX_VALUE;
            for (int i = 0; i < strs.length; i++) {
                minLen = Math.min(strs[i].length(), minLen);
            }
            boolean flag = true;
            while (flag && res < minLen) {
                char c = strs[0].charAt(res);
                for (int j = 1; j < strs.length; j++) {
                    if (strs[j].charAt(res) != c) {
                        flag = false;
                        break;
                    }
                }

                if (flag) res++;
            }

            return strs[0].substring(0, res);
        }
    }
}
